#include "PatientModel.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QDate>

PatientModel::PatientModel(QObject *parent)
    :QAbstractListModel(parent){

}

int PatientModel::rowCount(const QModelIndex &parent) const
{
    //返回一共有多少数据
    return m_data.size();
}

QVariant PatientModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid()||role!=Qt::DisplayRole){
        return {};
    }
    //取到index所在的数据
    return QVariant::fromValue(m_data.at(index.row()));

}

void PatientModel::LoadFromDatabase(const QString &dp_path)
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName(dp_path);

    if(!db.open()){
        qWarning() << "Database error:" << db.lastError().text();
        return;
    }

    //sql查询语句
    QSqlQuery query;
    query.exec("SELECT name,gender,birthday,phone,email,address,annotation,create_time,first_name,last_name FROM Patient");

    while(query.next()){
        PersonData person;
        person.name=query.value(0).toString();
        person.gender=query.value(1).toInt();
        person.birthday=query.value(2).toString();
        person.phone=query.value(3).toString();
        person.email=query.value(4).toString();
        person.address=query.value(5).toString();
        person.annotation=query.value(6).toString();
        person.create_time=query.value(7).toString();
        person.first_name=query.value(8).toString();
        person.lastname=query.value(9).toString();

        //年龄通过birthday计算,
        QString birth_year=person.birthday.left(4);


        m_data.push_back(person);
    }
    db.close();


}
